package com.chy.blog_server.core.interceptor;

import com.chy.blog_server.core.util.UserUtil;
import com.chy.blog_server.modular.system.entity.SysUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 登录拦截器
 */
public class UserLoginInterceptor implements HandlerInterceptor {

    protected Logger logger = LoggerFactory.getLogger(UserLoginInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler)throws Exception {

        logger.info("--------------------登录拦截器已启动-------------------------");

        // 获取请求的URI
        String requestURI = request.getRequestURI();

        // 排除的URL列表，例如登录接口
        String[] excludeUrls = {"/map/publicIndex", "/map/publicMapMerchantInfo", "/map/publicMapDistrict", "/map/publicMapLog"};
        boolean shouldExclude = false;

        // 检查请求是否在排除列表中
        for (String url : excludeUrls) {
            if (requestURI.startsWith(url)) {
                shouldExclude = true;
                break;
            }
        }
        if (shouldExclude) {
            // 如果是排除的URL，则不进行拦截，直接返回true
            return true;
        }else{
            HttpSession session = request.getSession(true);
            //获取当前登录用户
            SysUser sysUser = (SysUser)session.getAttribute(UserUtil.USER_NAME_IN_SESSION);
            if(null != sysUser) {//已登录
                return true;
            }else {//未登录
                //直接重定向到登录页面
                response.sendRedirect(request.getContextPath()+"/sys/login");
                return false;
            }
        }
    }
}
